package com.bridgeintelligent.tag.engine.mvc.service.impl;

import com.bridgeintelligent.tag.engine.api.EngineConfig;
import com.bridgeintelligent.tag.engine.api.IndexNameInfo;
import com.bridgeintelligent.tag.engine.core.cache.CacheConfig;
import com.bridgeintelligent.tag.engine.core.cache.CacheUtils;
import com.bridgeintelligent.tag.engine.es.base.ESQueryUtils;
import com.bridgeintelligent.tag.engine.es.model.CustomerDetailModel;
import com.bridgeintelligent.tag.engine.mvc.service.ICustomerDetailService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.Strings;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
@AllArgsConstructor
public class CustomerDetailServiceImpl implements ICustomerDetailService {

    @Override
    public Map<String, Object> customerDetail(CustomerDetailModel model) throws IOException {
        String queryKey = model.getQueryKey();
        //封装BoolQueryBuilder
        QueryBuilder queryBuilder = null;
        if (queryKey.length() == 19) {
            queryBuilder = QueryBuilders.termQuery(EngineConfig.CUST_NO, queryKey);
        }
        if (queryKey.length() == 10) {
            queryBuilder = QueryBuilders.termQuery(EngineConfig.ECIF_ID, queryKey);
        }
        //根据主题从缓存中获取索引名
        IndexNameInfo indexNameInfo = CacheUtils.getCacheInfo(CacheConfig.CONFIGURATION_INFO, "1");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //设置包含项
        String[] includes = model.getFields().split(",");
        searchSourceBuilder.query(queryBuilder).trackTotalHits(true).size(1).fetchSource(includes, Strings.EMPTY_ARRAY);

        SearchRequest searchRequest = new SearchRequest(indexNameInfo.getDataDate()).source(searchSourceBuilder);

        SearchResponse response = ESQueryUtils.getClient().search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        Map<String,Object> result = new HashMap<>();
        for (SearchHit searchHit : hits) {
            Map<String, Object> sourceMap = searchHit.getSourceAsMap();
            result.putAll(sourceMap);

        }
        return result;
    }
}
